package com.dzu.gulimall.search.thread;

import java.util.concurrent.*;

/**
 * @author ZhaoDong
 * @date 2022/4/24 17:45
 * @description 线程池测试
 */
public class ThreadTest2 {

    public static ExecutorService service = Executors.newFixedThreadPool(10);


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("start");
//        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
//            int i = 10;
//            while (i > 0) {
//                System.out.println(i);
//                i /= 3;
//            }
//        }, service);

        /**
         * 方法完成后的感知
         */
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            int i = 10;
//            while (i > 0) {
//                System.out.println(i);
//                i /= 0;
//            }
//            return i;
//            // whenComplete 执行当前任务的线程继续执行 和 whenCompleteAsync 这个就会用新的线程，或者指定线程池里的
//        }, service).whenComplete((res, exception) -> {
//            System.out.println("结果+" + res + "异常" + exception);
//
//            // exceptionally 有异常后可以处理，并且返回个默认值啥的
//        }).exceptionally(throwable -> 999);


        /**
         * 方法完成后的处理
         */

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            int i = 10;
            while (i > 0) {
                System.out.println(i);
                i /= 3;
            }
            return i;
            // whenComplete 执行当前任务的线程继续执行 和 whenCompleteAsync 这个就会用新的线程，或者指定线程池里的
        }, service).handle((res, exception) -> {
            if (res != null) {
                return res + 999;
            }
            if (exception != null) {
                return -1;
            }
            return 0;
        });

        System.out.println("end" + future2.get());
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            int i = 10;
            while (i > 0) {
                System.out.println(i);
                i /= 3;
            }
        }
    }

    public static class Runnable01 implements Runnable {

        @Override
        public void run() {
            int i = 10;
            while (i > 0) {
                System.out.println(i);
                i /= 3;
            }
        }
    }

    public static class Callable01 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            int i = 10;
            while (i > 0) {
                i /= 3;
            }
            return i;
        }
    }

}
